<template>
    <!-- 导航栏 -->
    <van-nav-bar
      title="个人资料"
      left-text="返回"
      left-arrow
      @click-left="back"
    />

    <!-- 个人头像 -->
    <div class="user">
        <div class="user-image">
          <img v-if="LoginUser.avatar" :src="LoginUser.avatar" />
          <img v-else src="/assets/images/01.jpg" />
        </div>
    </div>

    <!-- 表单内容 -->
    <div class="form">
        <van-form @submit="profile">
            <!-- 昵称 -->
            <div class="item">
              <van-field
                v-model="LoginUser.nickname" 
                name="nickname"
                label="昵称"
                placeholder="请输入昵称" 
                :rules="rules.nickname"
                />
            </div>

            <!-- 邮箱 -->
            <div class="item">
              <van-field
                v-model="LoginUser.email"
                name="email"
                placeholder="请输入登录邮箱"
                label="邮箱"
                :rules="rules.email"
              />
            </div>

            <!-- 密码 -->
            <div class="item">
              <van-field
                v-model="password"
                name="password"
                type="password"
                placeholder="请输入密码"
                label="密码"
              />
            </div>

            <!-- 性别 -->
            <div class="item">
              <van-field name="sex" label="性别">
                <template #input>
                  <van-radio-group v-model="LoginUser.sex" direction="horizontal">
                    <van-radio name="1">男</van-radio>
                    <van-radio name="2">女</van-radio>
                    <van-radio name="0">保密</van-radio>
                  </van-radio-group>
                </template>
              </van-field>
            </div>

            <!-- 地区 -->
            <div class="item">
              <van-field
                name="region_text"
                label="地区选择"
                placeholder="点击选择省市区"
                is-link
                readonly
                v-model="LoginUser.region_text"
                @click="ShowArea = true"
              />
            </div>

            <!-- 个人简介 -->
            <div class="item">
              <van-field
                v-model="LoginUser.content"
                rows="2"
                name="content"
                label="个人简介"
                type="textarea"
                placeholder="请输入个人简介"
                maxlength="50"
                show-word-limit
              />
            </div>

            <!-- 头像 -->
            <div class="item">
              <van-field name="avatar" label="头像修改">
                <template #input>
                  <!-- 文件上传的组件 -->
                  <van-uploader
                    v-model="avatar"
                    :max-count="1"
                  />
                </template>
              </van-field>
            </div>

            <!-- 背景封面 -->
            <div class="item">
              <van-field name="cover" label="背景封面">
                <template #input>
                  <!-- 文件上传的组件 -->
                  <van-uploader
                    v-model="cover"
                    :max-count="5"
                    :before-delete="del"
                    :after-read="add"
                  />
                </template>
              </van-field>
            </div>

            <div style="width:50%;margin:0 auto;">
              <van-button round block type="primary" native-type="submit">
                修改资料
              </van-button>
            </div>
        </van-form>
    </div>

    <!-- 引入地区弹出层 -->
    <van-popup v-model:show="ShowArea" position="bottom">
      <!-- 地区组件 -->
      <van-area
        :value="region"
        :area-list="areaList"
        @confirm="SelectRegion"
        @cancel="ShowArea = false"
      />
    </van-popup>
</template>

<script>
  // 引入地区初始化数据
  import { areaList } from '@vant/area-data';
  export default {
    name: 'BaseProfile',
    created()
    {
      var cover = this.$cookies.get('LoginUser').cover
      var list = []
      for(var item of cover)
      {
        list.push({
          url: item
        })
      }

      this.cover = list
    },
    data(){
      return {
        areaList,
        ShowArea: false,
        password:'',
        LoginUser:this.$cookies.get('LoginUser'),
        avatar:[
          {url: this.$cookies.get('LoginUser').avatar}
        ],
        cover:[],
        rules:{
          nickname: [
            {
              required:true,
              message:'请输入昵称'
            }
          ],
          email:[
            {
              required: true,
              message: '请输入登录邮箱'
            },
            {
              message: '邮箱输入的格式有误',
              validator(value)
              {
                //正则表达式
                var reg = new RegExp("^[a-z0-9]+([._\\-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$")

                //test方法返回true 和 false 
                return reg.test(value)
              }
            }
          ],
        }
      }
    },
    computed:{
      region()
      {
        var province = this.LoginUser.province
        var city = this.LoginUser.city
        var district = this.LoginUser.district

        var region = ''

        //判断是否有选择省份，就把省份赋值给变量
        if(province)
        {
          region = province
        }

        if(city)
        {
          region = city
        }

        if(district)
        {
          region = district
        }

        return region.toString()
      },
      //删除图片
      del()
      {
        return async (detail) => {
          //组装数据
          var data = {
            action:'del',
            userid: this.LoginUser.id,
            url: detail.url
          }

          //同步
          var result = await this.$api.cover(data)

          if(result.code == 0)
          {
            this.$notify({
              message:result.msg,
              duration:1000,
            })

            return false
          }

          //将cookie覆盖
          this.$cookies.set('LoginUser', result.data)

          var cover = result.data.cover
          var list = []
          for(var item of cover)
          {
            list.push({
              url: item
            })
          }

          this.cover = list
          return true
        }
      },
      //添加图片
      add()
      {
        return async (file, detail) => {

          //组装数据
          var data = {
            action:'add',
            userid: this.LoginUser.id,
            cover: file.file
          }

          //同步
          var result = await this.$api.cover(data)

          if(result.code == 0)
          {
            this.$notify({
              message:result.msg,
              duration:1000,
            })

            return false
          }

          //将cookie覆盖
          this.$cookies.set('LoginUser', result.data.data)

          var cover = result.data.data.cover
          var list = []
          for(var item of cover)
          {
            list.push({
              url: item
            })
          }

          this.cover = list
          return true
        }
      }
    },
    methods:{
      back()
      {
        this.$router.go(-1)
      },
      //选择地区的方法
      SelectRegion(value)
      {
        //点击确认同样也要隐藏弹出层
        this.ShowArea = false

        //将确认的结果 分别给到省市区
        let [province, city, district] = value

        var region_text = ''

        if(province)
        {
          this.LoginUser.province = province.code
          region_text += `${province.name}/`
        }

        if(city)
        {
          this.LoginUser.city = city.code
          region_text += `${city.name}/`
        }

        if(district)
        {
          this.LoginUser.district = district.code
          region_text += `${district.name}`
        }

        this.LoginUser.region_text = region_text
      },
      //提交个人资料
      async profile(form)
      {
        //封装数据
        var data = {
          id: this.LoginUser.id,
          nickname: form.nickname,
          email:form.email,
          sex:form.sex,
          content:form.content,
          province:this.LoginUser.province,
          city:this.LoginUser.city,
          district:this.LoginUser.district,
        }

        // 为空不修改密码，只有不为空的时候才修改
        if(form.password)
        {
          data.password = form.password
        }

        //如果有选择图片就上传
        if(form.avatar[0].file)
        {
          data.avatar = form.avatar[0].file
        }

        var cover = {}

        if(form.cover.length > 0)
        {
          form.cover.map((file, index) => {
            if(file.hasOwnProperty('file'))
            {
              cover[index] = file.file
            }
          })
        }
        
        data.cover = cover

        var result = await this.$api.profile(data)
       

        if(result.code == 0)
        {
          this.$notify({
            message:result.msg,
            duration:1000,
          })
        }else
        {
          this.$notify({
            type:'success',
            message:result.msg,
            duration:1000,
            onClose: () => {
              //将cookie覆盖
              this.$cookies.set('LoginUser', result.data)

              //跳转会会员中心
              this.$router.go(-1)
            }
          })
        }
      },
    }
  }
</script>

<style>
  @import url('/public/assets/css/profile.css');

</style>